#include "appmainwindow.h"
#include "ui_appmainwindow.h"
#include "QDebug"
#include "QFileDialog"
#include "cruncommand.h"
#include <QCloseEvent>
#include <QUrl>
#include <QMessageBox>



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_pRunCommand( new CRunCommand( this ) )
{
    ui->setupUi(this);
    ui->label->setBuddy( ui->lineEditIsoPath );
    ui->label_2->setBuddy( ui->lineEditMountLocation );
    ui->pushButtonExit->hide();

    this->mpSysIcon = new QSystemTrayIcon( QIcon(":/icons/icon.png") , this );
    connect( this->mpSysIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
             this, SLOT( onSysTraiActivated( QSystemTrayIcon::ActivationReason ) ));

    QAction *openAct = new QAction( tr("Exit.."), this);
    connect(openAct, SIGNAL(triggered()), this, SLOT( quitApplication()) );

    mpIconMenu = new QMenu( this );
    mpIconMenu->addAction(openAct);

    this->mpSysIcon->setContextMenu( mpIconMenu );
    this->mpSysIcon->setVisible( true );


    connect( ui->pushButtonIsoFile, SIGNAL(clicked()), this, SLOT( onIsoFileButtonClicked() ));
    connect( ui->pushButtonMountDir, SIGNAL(clicked()), this, SLOT( onMountDirButtonClicked() ));
    connect( ui->pushButtonThunar, SIGNAL(clicked()), this, SLOT( onThunarClicked() ));
    connect( ui->pushButtonVlc, SIGNAL( clicked()), this, SLOT( onVlcClicked() ) );

    connect( ui->lineEditIsoPath, SIGNAL(textChanged ( const QString &)), this, SLOT( checkOkButton() ));
    connect( ui->lineEditMountLocation,  SIGNAL(textChanged ( const QString &)), this, SLOT( checkOkButton() ));

    connect( ui->pushButtonMount, SIGNAL( clicked()), this, SLOT( onOkButtonPushed()) );
    connect( ui->pushButtonUMount, SIGNAL(clicked()), this, SLOT( onUNmount() ));

    connect( ui->pushButtonExit, SIGNAL(clicked()), this, SLOT( quitApplication() ) );
    connect( ui->actionExit, SIGNAL( triggered()), this, SLOT( quitApplication() ));

    ui->menuExit->addAction( ui->actionExit );


    // drag and drop
    setAcceptDrops(true);

    // populate mount locations
    populateMountLBrowser();

    // disable buttons
    this->checkOkButton();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onIsoFileButtonClicked(){

    QString fileName = QFileDialog::getOpenFileName(this, tr("Pick an Iso File"),
                                                    "/",
                                                    tr("disc image (*.iso);;All(*.*)"));
    ui->lineEditIsoPath->setText( fileName );
}

void MainWindow::onMountDirButtonClicked(){
    QString dirName = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
                                                        "/home",
                                                        QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    ui->lineEditMountLocation->setText( dirName );
}

void MainWindow::checkOkButton(){

    //
    //  check Mount button
    //
    if( !ui->lineEditIsoPath->text().isEmpty() &&
            !ui->lineEditMountLocation->text().isEmpty() )
    {
        ui->pushButtonMount->setEnabled( true );
    }
    else
    {
        ui->pushButtonMount->setEnabled( false );
    }


    //
    // check UMount button
    //
    if( !ui->lineEditMountLocation->text().isEmpty() )
    {
        ui->pushButtonUMount->setEnabled( true );
        ui->pushButtonThunar->setEnabled( true );
        ui->pushButtonVlc->setEnabled( true );
    }
    else{
        ui->pushButtonUMount->setEnabled( false );
        ui->pushButtonThunar->setEnabled( false );
        ui->pushButtonVlc->setEnabled( false );
    }
}

void MainWindow::onOkButtonPushed()
{

    QDir dir = QDir( ui->lineEditMountLocation->text() );

    if( dir.entryList( QDir::AllEntries | QDir::NoDotAndDotDot ).size() == 0 )
    {
        QString command;
        command.append( "mount -o loop  ");
        QString params = "\"" + ui->lineEditIsoPath->text() + "\"" + " " +
                "\"" + ui->lineEditMountLocation->text() + "\"";
        command.append( params );

        CRunCommand tRunCommand;

        tRunCommand.runSudoCommand( command );
    }
    else
    {
        QMessageBox::critical( 0, tr(" Critical "),
                               tr( "Mount location should be empty. Please choose another location" ),
                               QMessageBox::Ok );
    }

    populateMountLBrowser();
}

void MainWindow::onUNmount(){

    QString command;
    command.append( "umount ");
    QString params = "\"" + ui->lineEditMountLocation->text() + "\"";
    command.append( params );

    CRunCommand tRunCommand;
    tRunCommand.runSudoCommand( command );

    populateMountLBrowser();
}

void MainWindow::closeEvent ( QCloseEvent * event )
{
    event->ignore();
    this->hide();
    this->mpSysIcon->show();
}


void MainWindow::onSysTraiActivated( QSystemTrayIcon::ActivationReason reason ){

    if( reason == QSystemTrayIcon::Trigger )
    {
        if( this->isVisible() )
        {
            setVisible( false );
        }
        else{
            setVisible( true );
        }

    }

}


void MainWindow::quitApplication(){
    qApp->quit();
}


void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{

    if (event->mimeData()->hasUrls() )
    {
        QList< QUrl > urlList = event->mimeData()->urls();

        if( QFile::exists( urlList.at(0).path() ))
        {
            return event->acceptProposedAction();
        }


        if( QDir( urlList.at(0).path() ).exists() )
        {
            return event->acceptProposedAction();
        }
    }

    event->ignore();
}

void MainWindow::dropEvent(QDropEvent *event)
{
    if (event->mimeData()->hasUrls() )
    {
        QList< QUrl > urlList = event->mimeData()->urls();
        if( urlList.size() != 1 )
        {
            QMessageBox::warning( 0, tr(" Warning "),
                                  tr( "only first dir or file is accepted"),
                                  QMessageBox::Ok );
        }

        if( QDir( urlList.at(0).path() ).exists() )
        {
            ui->lineEditMountLocation->setText( urlList.at(0).path() );
            event->acceptProposedAction();
            return;
        }


        if( QFile::exists( urlList.at(0).path() ))
        {
            QFileInfo fileInfo = QFile( urlList.at(0).path() );
            qDebug() << fileInfo.suffix();
            if( fileInfo.suffix().compare( "iso" ) == 0 )
            {
                ui->lineEditIsoPath->setText( fileInfo.absoluteFilePath() );
                event->acceptProposedAction();
                return;
            }
        }

    }
    event->ignore();
}

void MainWindow::populateMountLBrowser(){
    ui->mountLTextBrowser->clear();
    QString result = m_pRunCommand->runCommand( "mount -l -t udf" );
    ui->mountLTextBrowser->setText( result );
}

void MainWindow::onThunarClicked(){
    m_pRunCommand->runCommandDetached( "thunar "+ ui->lineEditMountLocation->text() );
}

void MainWindow::onVlcClicked(){
    m_pRunCommand->runCommandDetached( "vlc "+ ui->lineEditMountLocation->text() );
}



